package com.yisen.study.shirostudy;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Tutorial {

    private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class);

    public static void main(String[] args) {
        log.info("My First Apache Shiro Application");

        //1.
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //2.
        SecurityManager securityManager = factory.getInstance();

        //3.
        SecurityUtils.setSecurityManager(securityManager);
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        // 取得当前会话，并设置key value
        Session session = currentUser.getSession();
        session.setAttribute( "someKey", "aValue" );
        // 检测当前用户是否登录，没有登录就进行登录
        if ( !currentUser.isAuthenticated() ) {
            // 用户传来的账号密码生成token
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            // 进行数据库等比对。查看是否正确。
            try {
                currentUser.login(token);
            } catch ( UnknownAccountException uae ) {
                // 账号不存在
            } catch ( IncorrectCredentialsException ice ) {
                // 密码不正确
            } catch ( LockedAccountException lae ) {
                // 账户被锁定
            } catch ( AuthenticationException ae ) {
                // 统一处理的意外情况。
            }
        }
        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("你拥有schwartz角色");
        } else {
            log.error("你没有schwartz角色");
        }

        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("你具有 lightsaber:wield 操作权限");
        } else {
            log.error("你没有 lightsaber:wield 操作权限");
        }

        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("你有 winnebago:drive:eagle5 权限");
        } else {
            log.error("你没有 winnebago:drive:eagle5 权限");
        }

        // 退出登录
        currentUser.logout();

        System.exit(0);
    }
}